Curl发送HTTP请求

小课堂

分享人:王蒙

目录

1.背景介绍

2.知识剖析

3.常见问题

4.解决方案

5.编码实战

6.扩展思考

7.参考文献

8.更多讨论

1.背景介绍

在linux上有多种接口测试工具,如restclient,httpie,ab等,在项目中最常用的是curl,用来进行简单的测试

2.知识剖析

2.1 curl

curl是很方便的Rest客戶端,可以很方便的完成許多Rest API测试的需求,利用curl指令,可以送出HTTP GET, POST, PUT, DELETE, 也可以改变 HTTP header来满足使用REST API需要的特定条件。

2.2 测试rest时常用的参数/p>

-X/--request [GET|POST|PUT|DELETE|…] 使用指定的HTTP method 发出指定的request

-H/--header “XX:XXX” 设定request的header

-i/--include 显示response的header

-d/--data “XX=XXX” 设定HTTP parameters

-v/--verbose 输出比较多的信息

-u/--user 使用者帐密

-b/--cookie 使用cookie

2.3 curl发送请求写法

-X后面加HTTP method,如:curl -X [GET|POST|PUT|DELETE] "http://www.jnshu.com" (纯英文、数字不用加引号,其他情况不加引号可能会出问题)

2.4 curl发送请求时可以附加一些信息

1)设置header:curl -i -H "Content-Type: application/json" http://www.jnshu.com/aaa

2)设置HTTP parameter:curl -X POST -d "param1=value1¶m2=value2" 或者 -d "param1=value1" -d "param2=value2"

3)session认证:curl -X GET 'http://www.jnshu.com/aaa' --header 'sessionid:1234567890987654321'

4) 使用cookie:curl -i --header "Accept:application/json" -X GET -b ~/cookie.txt http://www.jnshu.com/aaa

5) 文件上传:curl -i -X POST -F 'file=@/User/my_file.txt' -F 'name=file_name'

6) HTTP基本认证(HTTP Basic Authentication):curl -i --user username:password http://www.rest.com/api/foo'

2.5 wget访问HTTP资源

wget命令用来从指定的URL下载文件,访问接口时返回的数据会保存到本地。(自己测试可以访问GET和POST接口)

3.常见问题

实际使用

4.解决方案

在服务器上运行curl命令,加上url和相关参数

5.编码实战

6.扩展思考

curl发送POST请求时,数据可以采用xml格式或json格式, 并且可以发送本地的json和xml文件

1): curl -H 'content-type: application/json' -X POST -d '{"name":"shfbjsf"}' http://www.jnshu.com/aaa

2): curl -X POST -H 'content-type: application/json'  -d @/apps/jsonfile.json http://www.jnshu.com/aaa

3): curl -H 'content-type: application/xml' -X POST -d 'nksdnd' http://www.jnshu.com/aaa

4): curl -X POST -H 'content-type: application/json'  -d @/apps/xmlfile.json http://www.jnshu.com/aaa

7.参考文献

参考一:使用curl指令测试rest

参考二:使用curl进行接口测试

8.更多讨论

使用restclient,httpie,ab等工具测试rest

鸣谢

感谢大家观看

BY:王蒙

Contact GitHub API Training Shop Blog About © 2016 GitHub, Inc. Terms Privacy Security Status He